<script setup>
import { ref } from 'vue'
import { useRouter } from 'nuxt/app'
import { useForm } from 'vee-validate'
import { toTypedSchema } from '@vee-validate/zod'
import { UserRegisterSchema } from '@/schema/user.schema'
import github from '@/assets/images/github.svg'
import google from '@/assets/images/google.svg'
const requestURL = useRequestURL()
import * as z from 'zod'
const formSchema = toTypedSchema(z.object({
  username: z.string().min(2).max(50),
  password: z.string().min(6).max(50),
  email: z.string().min(2).max(50),
}))
definePageMeta({
  layout: 'auth'
})
const { fetchMe } = useAuth()
// 定义表单数据
const form = ref({
  name: '',
  email: '',
  password: '',
  agreePolicy: false,
})
const errs = ref([])
const router = useRouter()

const { data, error, execute, pending, status } = await useFetch('/api/auth/register', {
  method: 'POST',
  immediate: false,
  body: form.value,
})

const { handleSubmit, validate, errors } = useForm({
  validationSchema: toTypedSchema(UserRegisterSchema()),
})

const onSubmit = handleSubmit(async (values) => {
  console.log('values', values)
  await execute()
})

async function onValidating() {
  const result = await validate()
  if (!result.valid) return // ✅ 校验失败则中断

  const firstErrorField = Object.keys(errors.value)[0]
  if (firstErrorField) {
    const firstErrorFieldElement = document.querySelector(`[name=${firstErrorField}]`)
    if (firstErrorFieldElement) {
      firstErrorFieldElement.focus()
      firstErrorFieldElement?.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  }
  await onSubmit()
}
watch(status, async (newVal) => {
  if (newVal === 'success') {
    await fetchMe()
    router.push('/secure/dashboard')
  }
})
watch(error, (newVal) => {
  if (newVal?.data?.error) {
    if (newVal?.data?.statusCode === 400) {
      let _errors = []
      for (var issue of newVal?.data?.data) {
        _errors[issue.path[0]] = issue.message
      }
      errs.value = _errors
      return
    }
    const _err = (newVal?.data?.statusCode === 500)?'innerError':newVal?.data?.message
    errs.value = { innerError: _err }
  }
})
const loginGoogle = () => {
  window.location.href = '/api/auth/google/login'
}
</script>
<template>
  <section>
    <div class="flex relative justify-center lg:px-0 max-h-full md:px-12">
      <div
        class="px-4 relative flex flex-1 flex-col h-screen lg:py-24 md:flex-none md:px-28 py-10 sm:justify-center xl:py-32 z-10"
        style="height: calc(100vh - 5.25rem);"
      >
        <div class="w-full lg:h-full max-w-md md:max-w-sm md:px-0 md:w-96 mx-auto sm:px-4">
          <div class="flex flex-col">
            <div>
              <div class="py-3 relative">
                <div class="flex items-center absolute inset-0" aria-hidden="true">
                  <div class="w-full border-t opacity-60"></div>
                </div>
                <div class="flex relative justify-center">
                  <span class="text-sm px-2">{{ $t('register.signupWith') }}</span>
                </div>
              </div>
              <div class="py-3 flex flex-row">
                <NButton
                  @click="loginGoogle"
                  btn="outline"
                  class="cursor-pointer basis-1/2 md:basis-1/1 justify-center py-2 rounded outline-none focus:outline-none mr-2 mb-1 uppercase shadow hover:shadow-md inline-flex items-center text-xs ease-linear transition-all duration-150"
                  type="button"
                >
                  <img alt="..." class="w-5 mr-1" :src="google" />
                  Google
                </NButton>
                <router-link
                  to="/github"
                  class="cursor-pointer basis-1/2 md:basis-1/1 light:text-primary dark:bg-primary justify-center py-2 rounded outline-none focus:outline-none mr-2 mb-1 uppercase shadow hover:shadow-md inline-flex items-center text-xs ease-linear transition-all duration-150"
                >
                  <img alt="..." class="w-5 mr-1" :src="github" />
                  Github
                </router-link>
              </div>
              <div class="py-3">
                <div class="py-3 relative">
                  <div class="flex items-center absolute inset-0" aria-hidden="true">
                    <div class="w-full border-t opacity-60"></div>
                  </div>
                  <div class="flex relative justify-center">
                    <span class="text-sm px-2 bg-default text-primary-light">
                      {{ $t('register.orSignUpWithCredentials') }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <form @submit.prevent="onValidating()">
            <input name="hidden" autocomplete="false" style="display: none" />
            <input name="_redirect" type="hidden" value="#" />
            <div class="space-y-6">
              <NFormField
                name="name"
                :status="errs['name'] ? 'error' : undefined"
                :message="errs['name']"
              >
                <NInput
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('register.name')"
                  v-model="form.name"
                  autofocus
                />
              </NFormField>
              <NFormField
                name="email"
                :status="errs['email'] ? 'error' : undefined"
                :message="errs['email']"
              >
                <NInput
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('register.email')"
                  v-model="form.email"
                  autofocus
                />
              </NFormField>
              <NFormField
                name="password"
                :status="errs['password'] ? 'error' : undefined"
                :message="errs['password']"
              >
                <NInput
                  type="password"
                  class="w-full focus:outline-none border py-3 appearance-none h-12 block px-3 rounded-xl sm:text-sm"
                  :placeholder="$t('register.password')"
                  v-model="form.password"
                  autofocus
                />
              </NFormField>
              <NFormField
                name="agreePolicy"
                :status="errs['agreePolicy'] ? 'error' : undefined"
                :message="errs['agreePolicy']"
              >
                <NCheckbox 
                  class="rounded ml-1 w-5 h-5 ease-linear transition-all duration-150"
                  v-model="form.privacyPolicy"
                >
                  <span class="ml-2 text-sm">
                    {{ $t('register.iAgreeWithThe') }}
                    <a :href="`${requestURL && requestURL.origin}/policy`" class="hover:text-primary-600 text-primary font-semibold">
                      {{ $t('register.privacyPolicy') }}
                    </a>
                  </span>
                </NCheckbox>
              </NFormField>
              <div>
              <NAlert icon alert="soft-error" v-if="errs['innerError']">
                <label class="inline-flex items-center">
                  <i class="fa-solid fa-triangle-exclamation pr-2"></i>
                  {{ $t(errs['innerError']) }}
                </label>
              </NAlert>
              </div>
              <div class="text-center mt-6">
                  <NButton type="submit"
                    class="text-sm font-bold uppercase px-6 py-3 rounded shadow hover:shadow-lg outline-none mr-1 mb-1 w-full ease-linear transition-all duration-150"
                    :loading="status=='pending' && pending"
                >
                  {{ $t('register.createAccount') }}
                  </NButton>
                </div>
              <div class="flex items-center justify-between">
                <span class="font-medium text-sm leading-tight">
                  {{ $t('register.hasAMember' )}}
                  <router-link to="/login" class="thover:text-primary-600 text-primary ml-3">{{ $t('register.loginAccount') }}</router-link>
                </span>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>
  </section>
</template>